package com.glodon.paas.account.biz.impl;

import static com.glodon.paas.consts.DatabaseConst.DEFAULT_LIMIT_S;
import static com.glodon.paas.consts.DatabaseConst.ORDER_BY_DESC_INT;

import java.util.Date;
import java.util.List; 

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
 
import com.glodon.paas.account.dao.CommunicateBookDao;
import com.glodon.paas.account.dao.UserDao;
import com.glodon.paas.account.dao.domain.CommunicateEntity;
import com.glodon.paas.account.dao.domain.UserEntity;
import com.glodon.paas.consts.DatabaseConst;
import com.glodon.paas.exception.BaseErrorException; 
import com.glodon.paas.exception.PaasServerExceptionFactory;
import com.glodon.paas.exception.i18n.ErrorCode;
import com.glodon.paas.util.UUIDUtil;

@Component("communicateBookBiz")
public class CommunicateBookBizImpl {
	private static Logger logger = LoggerFactory.getLogger(CommunicateBookBizImpl.class);

	@Autowired
	private CommunicateBookDao communicateBookDao;
	@Autowired
	UserDao userDao;

	/**
	 * 新增联系人，存在
	 * 
	 * @param communicateEntity
	 * @param updateIfExis
	 * 
	 * @return 返回数据库的ID
	 * @throws BaseErrorException 
	 */
	public String add(CommunicateEntity communicate, boolean updateIfExis){
		String temp = null;
		
		//****** 判断属性完整性 ******
		if(communicate.getUserId() == null){
			logger.error("userId is null");
			throw PaasServerExceptionFactory.validateException("userId is null", null);
		}
		
		if(communicate.getContactId() == null){			
			logger.error("contactId is null");
			throw PaasServerExceptionFactory.validateException("contactId is null", null);
		}
		
		if(communicate.getUserId().equals(communicate.getContactId())){
			//return null;
			throw PaasServerExceptionFactory.validateException("con not add self to CommunicateBook", null).setErrorCode(ErrorCode.CANNOT_ADD_SELF);
		}
		
		//****** 判断关系是否存在 ******
		CommunicateEntity objDb = queryByContactId(communicate.getUserId(), communicate.getContactId());		 
		if(objDb != null){
			if(updateIfExis){
				updateRemark(objDb.getId(), communicate.getRemarkName(), communicate.getRemarkText());
			}else{
				//TODO 关系已存在
				throw PaasServerExceptionFactory.existException("communicate exist", null);
			}
			return objDb.getId();
		}
		
		//****** 获取账户Email ******
		UserEntity userDb = userDao.get(communicate.getContactId());
		if(userDb != null){
			communicate.setContactEmail(userDb.getEmail());
		}else{
			throw PaasServerExceptionFactory.notFoundException("communicate not exist",null);
		}
		
		//****** 备注名处理 ******
		temp = communicate.getRemarkName();
		if(temp == null || temp.trim().length() == 0){
			communicate.setRemarkName(communicate.getContactEmail());
		}
		
		//****** 排序序号处理 ******
		List<CommunicateEntity> list = communicateBookDao.selectByUserId(
				communicate.getUserId(),
				DatabaseConst.ORDER_BY_DESC_INT, 
				0, 1);
		if(list.size() == 0){
			communicate.setOrderNum(1);
		}else{
			communicate.setOrderNum(list.get(0).getOrderNum()+1);
		}
		
		if(StringUtils.isBlank(communicate.getId())){
			communicate.setId(UUIDUtil.getUUIDStr());
		}
		return communicateBookDao.insert(communicate);
	};
	
	
	/**
	 * 根据userId查询其联系人列表
	 * 
	 * @param userId        当前用户id
	 * @param orderType     1顺序,-1逆序,其他使用数据库排序
	 * @param startIndex
	 * @param count
	 * @return
	 */
	public List<CommunicateEntity> query(
			String userId,
			Integer orderType,
			Integer startIndex, 
			Integer count
			){// 参数校验
		if (startIndex == null) {
			startIndex = 0;
		}
		if (count == null) {
			count = DEFAULT_LIMIT_S;
		}
		if (orderType == null) {
			orderType = ORDER_BY_DESC_INT;
		} 
		return communicateBookDao.selectByUserId(userId, orderType, startIndex, count);
	};
	
	
	/**
	 * 根据contactId查询其联系人
	 * 
	 * @param userId
	 * @param contactId 
	 * @return
	 */
	public CommunicateEntity queryByContactId(
			String userId,
			String contactId
			){
		return communicateBookDao.selectByContactId(userId, contactId);
	};
	
	/**
	 * 根据id查询其联系人
	 * 
	 * @param userId
	 * @param contactId 
	 * @return
	 */
	public CommunicateEntity queryById(
			String id
			){
		return communicateBookDao.get(id);
	};
	
	/**
	 * 统计联系人数量
	 * 
	 * @param userId
	 * @return
	 */
	public long count(String userId){
		return communicateBookDao.countByUserId(userId);
	}

	/**
	 * 判断两个人关系
	 * 返回1： contactId是userId的联系人
	 * 返回0： 没任何关系
	 * 
	 * @param userId
	 * @param contactId
	 * @return 
	 */
	public int judge(String userId, String contactId){
		if(userId == null || contactId == null){
			return 0;
		}
		CommunicateEntity db = communicateBookDao.selectByContactId(userId, contactId);
		if(db!=null){
			return 1;
		}else{
			return 0;			
		}		 
	}
	
	public int removeById(String id){
		if(id == null){
			return 0;
		}
		return communicateBookDao.delete(id);
	}
	
	/** 
	 * 根据userId，contactId删除单条联系人
	 * 
	 * @param userId
	 * @return
	 */
	public int remove(String userId, String contactId){
		if(userId == null || contactId == null){
			return 0;
		}
		return communicateBookDao.deleteByContactId(userId, contactId);
	} 
	
	
	/**
	 * 根据id对非空属性更新，当前只能更新以下属性
	 * remarkName
	 * remarkText
	 * 
	 * @return 更新记录数
	 */
	public int updateRemark(
			String id, 
			String remarkName, 
			String remarkText){
		if(remarkName==null && remarkText==null){
			return 0;
		}
		
		CommunicateEntity communicate = new CommunicateEntity();
		communicate.setId(id);
		communicate.setRemarkName(remarkName);
		communicate.setRemarkText(remarkText);
		communicate.setUpdateTime(new Date());
		
		return communicateBookDao.updateById(communicate );
	};
	
	/**
	 * 重排序
	 * 
	 * @param id
	 * @param newOrder		新位置
	 * @param orderType		排序方式
	 * @return 
	 */
	public int updateOrder(
			String id, 
			Integer newOrder, 
			Integer orderType
			){
		
		return 0;
	};
}
